<template>
  <div class="trend-chart">
    <van-cell-group inset title="趋势分析">
      <div class="chart-container">
        <div ref="chartRef" class="chart"></div>
      </div>
    </van-cell-group>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  MarkPointComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  MarkPointComponent,
  LineChart,
  CanvasRenderer
])

const props = defineProps({
  data: {
    type: Array,
    required: true
  },
  title: {
    type: String,
    required: true
  },
  unit: {
    type: String,
    required: true
  }
})

const chartRef = ref(null)
let chart = null

const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  updateChart()
}

const updateChart = () => {
  if (!chart || !props.data.length) return

  const dates = props.data.map(item => item.time.substring(5, 10))
  const values = props.data.map(item => item.value)

  const option = {
    title: {
      text: props.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const [param] = params
        return `${param.name}<br/>${param.value}${props.unit}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: props.unit,
      scale: true
    },
    dataZoom: [
      {
        type: 'inside',
        start: Math.max(0, 100 - (1000 / props.data.length)),
        end: 100
      },
      {
        start: Math.max(0, 100 - (1000 / props.data.length)),
        end: 100
      }
    ],
    series: [
      {
        type: 'line',
        data: values,
        smooth: true,
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        }
      }
    ]
  }

  chart.setOption(option)
}

watch(() => props.data, updateChart, { deep: true })

onMounted(() => {
  initChart()
  window.addEventListener('resize', () => chart?.resize())
})

onUnmounted(() => {
  chart?.dispose()
  window.removeEventListener('resize', () => chart?.resize())
})
</script>

<style lang="scss" scoped>
.trend-chart {
  .chart-container {
    padding: 16px;
    background-color: #fff;
    
    .chart {
      width: 100%;
      height: 300px;
    }
  }
}
</style> 